!function () {
    var $ = mdui.$;

    class T {
        constructor(el) {
            this.fluid = $(`<div class="mdui-table-fluid mdui-table-hoverable ds-table"></div>`);
            this.table = $(`<table class="mdui-table mdui-table-selectable"></table>`);
            this.head = $(document.createElement("thead"));
            this.headTr = $(`<tr></tr>`);
            this.body = $(`<tbody></tbody>`);
            this.loading = $(`<div class='ds-table-loading'><div class="mdui-spinner"></div></div>`);

            this.head.append(this.headTr);
            this.table.append(this.head)
            this.table.append(this.body);
            this.fluid.append(this.table);
            el.append(this.fluid[0]);

            this.callback = new Map();
        };
        addField(name) {
            this.headTr.append(`<th>${name}</th>`)
        };
        addRow(data) {
            var row = this.body.find("tr").length;
            var tr = $(`<tr></tr>`);
            for (let index in data) {
                let value = data[index];
                let th = $(`<td></td>`);
                th.on("click", () => {
                    this._emit("cellClick", {
                        line: Number(index),
                        row
                    });
                });
                if (typeof value == "object" && value != null) {
                    if (value.type == "text") {
                        th.text(value.text);
                    } else if (value.type == "html") {
                        th.html(value.text);
                    } else if (value.type == "el") {
                        th.append(value.el);
                    }
                } else {
                    th.text(String(value));
                }
                tr.append(th);
            }
            tr.on("click", () => {
                this._emit("rowClick", {
                    row
                });
            });
            this.body.append(tr);
            mdui.updateTables()
        };
        clear() {
            this.body.html('')
        };
        startLoading() {
            this.body.append(this.loading);
        };
        endLoading() {
            this.loading.remove();
        };
        getCell(row, line) {
            return $($(this.body.find("tr")[row]).find("td")[line + 1]).text();
        };
        setCell(row, line, text) {
            $($(this.body.find("tr")[row]).find("td")[line + 1]).text(text);
        };
        on(event, callback) {
            this.callback.set(callback, event);
        };
        off(callback) {
            this.callback.delete(callback);
        };
        _emit(name, event) {
            this.callback.forEach((val, key) => {
                if (val == name) {
                    key(event);
                }
            })
        }
    }

    window.table = {
        T
    }
}()